import React, { Component } from "react"
import { connect } from 'react-redux'
import { messages } from "share/common";
import { wrappedRowSelection } from 'components/table/table-row-selection'
import Template from "components/UI/template"
import { Tabs, Radio, message, notification, Icon } from 'antd'
import confirmSumptionService from './confirm-consumption.service'
import AdvancedTable from 'components/advanced-table'
import columnsListData from './columns-list-data'
import 'styles/confirm-consumption/index.scss'
import {batchOperations} from "components/template/wrapped-table-params/batch-operations";
import errorMessage from "share/errorMessage";
import FeedbackModal from "./feedback-modal";
import SlideFrame from "components/slide-frame";
import ConsumptionDetail from './confirm-consumption-detail'

const { Header, Middle } = Template;
const { TabPane } = Tabs;
const SimpleTable = AdvancedTable.SimpleTable;

class ConfirmConsumption extends Component {

  state = {
    status: 'air',
    confirmType: '0',
    tabList: {
      air: { title: messages('expense-16.key328')/*机票账单*/, num: 0 },
      hotel: { title: messages('expense-16.key329')/*酒店账单*/, num: 0 },
      train: { title: messages('expense-16.key438')/*火车账单*/, num: 0 },
      car: { title:messages('expense-16.key330')/*用车账单*/, num: 0},
      dining: { title: messages('expense-16.key439')/*用餐账单*/, num: 0 },
    },
    columns: [],
    confirmReason: '',
    selectedRowKeys: [],
    selectedData: {},
    showSlideFrame: false
  };

  notificationMsg = {
    'Success': messages('expense-16.key466')/*确认成功*/,
    'Error': messages('expense-16.key467')/*确认失败*/,
    'PartialError': messages('expense-16.key468')/*确认部分失败*/
  };

  componentWillMount() {
    this.getDispenseSumByUser();
  }

  getDispenseSumByUser = () => {
    let { tabList } = this.state;
    const { loginUser: { mobile, companyOID, employeeID, tenantId }} = this.props;
    let params = {
      companyOID,
      confirmType: '0',
      phone: mobile,
      employID: employeeID,
      tenantId: tenantId
    };
    confirmSumptionService.getDispenseSumByUser(params).then(res => {
      res.data.sums.map(i => tabList[Object.keys(i)[0]] && (tabList[Object.keys(i)[0]].num = i[Object.keys(i)[0]]));
    });
    this.setState({ tabList })
  };

  getConfirmDataList = (page, size) => {
    const { loginUser: { mobile, companyOID, employeeID, tenantId }} = this.props;
    const { confirmType, status } = this.state;
    let params = {
      page,
      size,
      companyOID,
      confirmType,
      phone: mobile,
      employID: employeeID,
      tenantId: tenantId,
      dispenseType: status
    };
    return new Promise((resolve => confirmSumptionService.getConfirmDataList(params).then(res => {
      res.data = res.data.records.filter(i => i.dispenseType === status);
      resolve(res);
    })
    ));
  };

  onFeedback = (dispenseId) => {
    const { selectedRowKeys } = this.state;
    const { loginUser: { employeeID, fullName, userOID }} = this.props;
    return new Promise((resolve, reject) => {
      FeedbackModal.open(this).then(confirmReason => {
        if(confirmReason === null) {
          reject();
          return;
        }
        this.setState({ btnLoading: { 'FEEDBACK': true } });
        let params = {
          confirmReason: confirmReason,
          confirmStatus: "203",
          dispenseIds: dispenseId ? [dispenseId] : selectedRowKeys,
          userId: employeeID,
          userName: fullName,
          userOID: userOID
        };
        confirmSumptionService.confirmDispense(params).then(res => {
          this.setState({ btnLoading: { 'FEEDBACK': false }, selectedRowKeys: [] });
          this.getDispenseSumByUser();
          this.advancedTableRef.getList();
          message.success(res.data.msg || (res.data.rows && res.data.rows.msg) || messages('common.operate.success')/*操作成功*/);
          resolve();
        }).catch(e => {
          this.setState({ btnLoading: { 'FEEDBACK': false } });
          errorMessage(e.response);
          reject();
        });
      }).catch(() => {
        message.warn(messages('expense-16.key331')/*请先输入反馈内容*/);
        reject();
      })
    });
  };

  onConfirm = dispenseId => {
    const { selectedRowKeys } = this.state;
    const { loginUser: { employeeID, fullName, userOID }} = this.props;
    let params = {
      confirmReason: '',
      confirmStatus: "201",
      dispenseIds: dispenseId ? [dispenseId] : selectedRowKeys,
      userId: employeeID,
      userName: fullName,
      userOID: userOID
    };
    this.setState({ btnLoading: { 'CONFIRM': true } });
    return new Promise((resolve, reject) => {
      confirmSumptionService.confirmDispense(params).then(res => {
        this.setState({ btnLoading: { 'CONFIRM': false }, selectedRowKeys: [] });
        this.showNotification({ data: res.data });
        this.advancedTableRef.getList();
        this.getDispenseSumByUser();
        resolve();
      }).catch(e => {
        reject();
        this.setState({ btnLoading: { 'CONFIRM': false } });
        errorMessage(e.response);
      });
    });
  };

  // 提交成功
  showNotification({type, data }) {
    let errMsg = data.errorMsg;
    let successNum = data.num;
    let errorNum = data.errorNum;
    let title = `${errorNum === 0 ? 'Success' : (data.num > 0 ? 'PartialError' : 'Error')}`;
    let description = () => {
      if(successNum === 0) return messages('expense-16.key470',{arg1: errorNum,arg2: errMsg})/*您有{arg1}笔单据确认失败, {arg2}*/;
      if(errorNum === 0) return messages('expense-16.key469',{arg1: successNum})/*您有{arg1}笔单据确认成功:)*/;
      return (
        <div>
          <p style={{margin: 0}}>{messages('expense-16.key471',{arg1: successNum})/*您有{arg1}笔单据确认成功*/}</p>
          <p style={{margin: 0}}>{messages('expense-16.key470',{arg1: errorNum,arg2: errMsg})/*您有{arg1}笔单据确认失败, {arg2}*/}</p>
        </div>
      );
    };
    notification.open({
      message: this.notificationMsg[title],
      description: description(),
      icon: <Icon type="smile-circle" className='default-color-font'/>,
      duration: 2,
    });
  };

  onSelectChange = ( selectedRowKeys ) => this.setState({ selectedRowKeys });

  openSlideFrame = record => {
    this.setState({ selectedData: record, showSlideFrame: true });
  };

  render() {
    const { status, tabList, selectedRowKeys, confirmType, selectedData, showSlideFrame } = this.state;
    let rowSelection = wrappedRowSelection({
      rowKey: 'dispenseId',
      selectedRowKeys
    }, this.onSelectChange);
    let tableParams =  batchOperations({
      rowKey: 'dispenseId'
    }, [{
      type: 'CONFIRM',
      btnName: messages('expense-16.key12')/*确认*/,
      service: confirmSumptionService.confirmDispense,
      onClick: this.onConfirm
    }, {
      type: 'FEEDBACK',
      btnName: messages('expense-16.key302')/*反馈异常*/,
      service: confirmSumptionService.batchOpenOrCloseExpensePrint,
      onClick: this.onFeedback
    }], this);

    tableParams = confirmType === '0' ? {...tableParams, rowSelection} : {};
    return (
      <Template className='confirm-consumption'>
        <Header>
          <Tabs
            type="card"
            defaultActiveKey={status}
            onChange={key => this.setState({ status: key }, this.advancedTableRef.getList)}
          >
            {['air', 'hotel', 'train', 'car', 'dining'].map(tab => (
              <TabPane key={tab} tab={(
                <div className='confirm-consumption-tab'>
                  <div>{tabList[tab].title}</div>
                  <div className='confirm-consumption-tab-subtitle'>
                    {messages('expense-16.key333')/*待处理*/}:&nbsp;<span className='default-color-inverse-font'>{tabList[tab].num}</span>{messages('expense-16.key52')/*笔*/}
                  </div>
                </div>
              )}/>
            ))}
          </Tabs>
        </Header>
        <Middle>
          <SimpleTable
            index
            show={['table-utils']}
            rowKey='dispenseId'
            tableName={'confirm-consumption'}
            onRef={ref => this.advancedTableRef = ref}
            service={this.getConfirmDataList}
            columns={columnsListData.columns[status]}
            {...tableParams}
            onRow={record => ({
              onClick: () => this.openSlideFrame(record)
            })}
          >
            <Radio.Group
              onChange={e => this.setState({ confirmType: e.target.value }, this.advancedTableRef.getList)}
              style={{ marginBottom: 16 }}
              defaultValue='0'
            >
              <Radio.Button value="0">{messages('expense-16.key333')/*待处理*/}</Radio.Button>
              <Radio.Button value="1">{messages('expense-16.key334')/*已处理*/}</Radio.Button>
            </Radio.Group>
          </SimpleTable>
          <SlideFrame
            content={ConsumptionDetail}
            onClose={() => this.setState({ showSlideFrame: false })}
            afterClose={() => this.setState({ showSlideFrame: false })}
            show={showSlideFrame}
            title={messages('expense-16.key332')/*消费数据详情*/}
            params={{
              dispenseType: selectedData.dispenseType,
              dispenseId: selectedData.dispenseId,
              recordId: selectedData.recordId,
              confirmType,
              show: showSlideFrame,
              onConfirm: this.onConfirm,
              onFeedback: this.onFeedback
            }}
            hasFooter={true}
            width="800px"
          />
        </Middle>
      </Template>
    )
  }

}

function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser
  }
}

export default connect(mapStateToProps)(ConfirmConsumption)
